<template>
  <div class="regMain">
    <div class="regCard">
      <div style=" margin-left: 200px; margin-right: 0px; user-select: none; margin-top: 8px;">
        <img src="../assets/logo2.jpg" style="height: 50%; width: 50%;" />
        <a style="margin-left: 100px;">
          <img src="../assets/ornament1.png" style="height: 20%; width: 20%;padding-right: 0px;" />
        </a>
      </div>

      <el-form ref="formData" :model="formData" style=" margin-top: 30px;" label-width="100px">

        <el-form-item label="昵称" prop="name">
          <el-input v-model="formData.username" prop="name" placeholder="这是你在知道社区的名字" @input="checkName">
            <a slot="prefix" class="el-input__icon el-icon-user"></a>
          </el-input>

          <img v-show="nameValid == 'valid'" src="../assets/correct2.png"
            style="vertical-align: middle; height:20px; width:20px; margin-left: 10px;" />
          <img v-show="nameValid == 'invalid'" src="../assets/wrong.jpg"
            style="height:20px; width:20px; vertical-align: middle; margin-left: 10px;" />
          <a class="nameHint" v-show="nameValid == 'valid'"
            style="vertical-align: middle; font-family: 'KaiTi'; color: #82D900;"><b>{{ messageNameCorrect }}</b></a>
          <a class="nameHint" v-show="nameValid == 'invalid'"
            style="vertical-align: middle; font-family: 'KaiTi'; color: #FF5151;"><b>{{ messageNameWrong }}</b></a>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" autocomplete="off" placeholder="这是唯一能够确认你身份的信息" @input="checkEmail">
            <a slot="prefix" class="el-input__icon el-icon-message"></a>
          </el-input>
          <img v-show="emailValid == 'valid'" src="../assets/correct2.png"
            style="vertical-align: middle; height:20px; width:20px; margin-left: 10px;" />
          <img v-show="emailValid == 'invalid'" src="../assets/wrong.jpg"
            style="height:20px; width:20px; vertical-align: middle; margin-left: 10px;" />
          <a class="nameHint" v-show="emailValid == 'valid'"
            style="vertical-align: middle; font-family: 'KaiTi';color: #82D900;"><b>{{ messageEmailCorrect }}</b></a>
          <a class="nameHint" v-show="emailValid == 'invalid'"
            style="vertical-align: middle; font-family: 'KaiTi'; color: #FF5151;"><b>{{ messageEmailWrong }}</b></a>
        </el-form-item>

        <el-form-item prop="verifycode">
          <el-button type="success" style="width: 150px;margin-left: 10px; height:39px;" @click="sendCode"
            :disabled="disabled">{{ buttonName }}</el-button>
          <el-input v-model="codeInput" autocomplete="off" placeholder="输入验证码" @input="checkEmail"
            style="width: 140px;margin-left: 10px; height:35px;">
            <a slot="prefix" class="el-input__icon el-icon-message"></a>
          </el-input>
        </el-form-item>

        <el-form-item label="学历" prop="education">
          <el-select v-model="formData.education" placeholder="请选择">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.label">
            </el-option>
            <a slot="prefix" class="el-input__icon el-icon-reading"></a>
          </el-select>
        </el-form-item>

        <el-form-item class="password" label="密码" prop="password">

          <el-input v-model="formData.password" show-password placeholder="好密码三要素：字母、数字、符号" @input="checkPassStrength">
            <a slot="prefix" class="el-input__icon el-icon-key"></a>
          </el-input>

          <img v-show="passwordlv == 3" src="../assets/correct2.png"
            style="vertical-align: middle; height:20px; width:20px; margin-left: 10px;" />
          <img v-show="passwordlv == 2" src="../assets/caution.jpg"
            style="vertical-align: middle; height:20px; width:20px; margin-left: 10px;" />
          <img v-show="passwordlv == 1" src="../assets/danger.jpg"
            style="vertical-align: middle; height:20px; width:20px; margin-left: 10px;" />
          <img v-show="passwordlv == 0" src="../assets/wrong.jpg"
            style="height:20px; width:20px; vertical-align: middle; margin-left: 10px;" />
          <a class="nameHint" v-show="passwordlv == 3"
            style="vertical-align: middle; font-family: 'KaiTi'; color: #82D900;"><b>{{ messagePassOK }}</b></a>
          <a class="nameHint" v-show="passwordlv == 2"
            style="vertical-align: middle; font-family: 'KaiTi'; color: #FFD306;"><b>{{ messagePassNormal }}</b></a>
          <a class="nameHint" v-show="passwordlv == 1"
            style="vertical-align: middle; font-family: 'KaiTi'; color: #FF9D6F;"><b>{{ messagePassWeak }}</b></a>
          <a class="nameHint" v-show="passwordlv == 0"
            style="vertical-align: middle; font-family: 'KaiTi'; color: #FF5151;"><b>{{ messagePassShort }}</b></a>
          <el-popover placement="top" title="好密码的要素" width="200" trigger="hover" content="我们把密码分为3个强度等级，字母、数字、符号中只包含一种则为弱密码，包含两种为中等密码，3种都包含为强密码。
            密码长度必须大于8，理论上密码越强越安全，但是弱密码和中等密码也可以完成注册，只是不推荐。
            ">
            <img src="../assets/help.jpg"
              style="vertical-align: middle; height:15px; width:15px; margin-left: 5px;cursor: pointer;"
              slot="reference" />
          </el-popover>
        </el-form-item>

        <el-form-item class="passwordAgain" label="确认密码">
          <el-input v-model="passwordAgain" show-password placeholder="确保你输对了" @input="verifyPassword">
            <a slot="prefix" class="el-input__icon el-icon-key"></a>
          </el-input>
          <img v-show="passwordVerified == 'yes'" src="../assets/correct2.png"
            style="vertical-align: middle; height:20px; width:20px; margin-left: 10px;" />
          <img v-show="passwordVerified == 'no'" src="../assets/wrong.jpg"
            style="height:20px; width:20px; vertical-align: middle; margin-left: 10px;" />
          <a class="nameHint" v-show="passwordVerified == 'yes'"
            style="vertical-align: middle; font-family: 'KaiTi';color: #82D900;"><b>{{ messagePassAgainCorrect
            }}</b></a>
          <a class="nameHint" v-show="passwordVerified == 'no'"
            style="vertical-align: middle; font-family: 'KaiTi'; color: #FF5151;"><b>{{ messagePassAgainWrong }}</b></a>
        </el-form-item>

        <el-form-item prop="submit" style=" margin-top: 20px;">
          <el-button type="primary" style="margin-right: 20px; width: 180px;margin-left: 10px; height:35px;"
            @click="submit">注册
          </el-button>
          <router-link class="list-group-item" active-class="active" to="/login">
            <el-button type="plain" style="margin-right: 10px; width: 100px; height:35px;">已有账号？</el-button>
          </router-link>
        </el-form-item>

      </el-form>
    </div>
  </div>
</template>

<script>
import { Message } from 'element-ui'
import request from '../API/request'
export default {
  data() {
    return {
      formData: {
        username: '',
        email: '',
        password: '',
        education: '',
      },
      count: 60,
      buttonName: '获取验证码',
      disabled: false,
      options: [
        { label: '博士毕业', value: '001' },
        { label: '博士在读', value: '002' },
        { label: '硕士毕业', value: '003' },
        { label: '硕士在读', value: '004' },
        { label: '本科毕业', value: '005' },
        { label: '本科在读', value: '006' },
        { label: '大专毕业', value: '007' },
        { label: '大专在读', value: '008' },
        { label: '高中毕业', value: '009' },
        { label: '高中在读', value: '010' },
        { label: '初中毕业', value: '011' },
        { label: '初中在读', value: '012' },
        { label: '小学及以下', value: '013' },
      ],
      passwordAgain: '',
      codeInput: '',
      codeCorrect: '',

      nameValid: '',
      emailValid: '',
      passwordlv: -1,
      passwordVerified: '',

      messageNameCorrect: '  这个昵称可用',
      messageNameWrong: '  昵称不可以为空',
      messageEmailCorrect: '  格式似乎是对的',
      messageEmailWrong: '  好像不是个邮箱吧',
      messagePassOK: '  好密码，请记牢！',
      messagePassNormal: '  还可以',
      messagePassWeak: '  密码太弱了',
      messagePassShort: '  至少要8位哦',
      messagePassAgainCorrect: '  看来你没写错',
      messagePassAgainWrong: '  和上面的不一样哦',
    }
  },
  methods: {
    checkName() {
      let rex = new RegExp('^[ ]+$')
      if (this.formData.username == '' || rex.test(this.formData.username)) {
        this.nameValid = 'invalid'
      } else {
        this.nameValid = 'valid'
      }
    },
    checkEmail() {
      console.log(this.emailValid)
      if (
        /^[a-zA-Z0-9]+([-_.][A-Za-zd]+)*@([a-zA-Z0-9]+[-.])+[A-Za-zd]{2,5}$/.test(
          this.formData.email
        )
      ) {
        this.emailValid = 'valid'
      } else {
        this.emailValid = 'invalid'
      }
    },
    checkPassStrength() {
      var pass = this.formData.password
      let lv = 0
      if (pass.match(/[a-z]/g)) {
        lv++
      } //包含字母
      if (pass.match(/[0-9]/g)) {
        lv++
      } //包含数字
      if (pass.match(/(.[^a-z0-9])/g)) {
        lv++
      } //包含符号
      if (pass.length < 8) {
        lv = 0
      } //密码长度不合格
      if (lv > 3) {
        lv = 3
      }
      this.passwordlv = lv
    },
    verifyPassword() {
      if (this.passwordAgain == this.formData.password)
        this.passwordVerified = 'yes'
      else this.passwordVerified = 'no'
    },

    timer() {
      var timeout = setInterval(() => {
        if (this.count < 1) {
          this.disabled = false
          this.buttonName = '发送验证码'
          this.count = 60
          clearInterval(timeout)
        } else {
          this.disabled = true
          this.buttonName = this.count-- + 's后重发'
        }
      }, 1000)
    },

    sendCode() {
      if (this.emailValid == 'invalid') {
        Message({
          message: '请先输入正确的邮箱',
          type: 'error',
          customClass: 'message-global',
        })
        return
      }
      const verificationRequest = async function (email) {
        return await request.get('/user/sendIC', {
          timeout: 30000,
          params: { mail: email },
        })
      }
      Message({
        message: '验证码已发送',
        type: 'success',
        customClass: 'message-global',
      })
      this.timer()
      verificationRequest(this.formData.email)
        .then((res) => {
          const result = res.data
          if (result.code === 200) {
            this.codeCorrect = result.data
          } else {
            Message({
              message: '发送失败',
              type: 'error',
              customClass: 'message-global',
            })
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },

    submit() {
      if (this.count == 60) {
        Message({
          message: '请先发送验证码',
          type: 'error',
          customClass: 'message-global',
        })
        return
      }

      if (this.nameValid == 'invalid' || this.nameValid == '') {
        Message({
          message: '用户名不能为空',
          type: 'error',
          customClass: 'message-global',
        })
        return
      }

      if (this.emailValid == 'invalid' || this.emailValid == '') {
        Message({
          message: '请输入正确的邮箱',
          type: 'error',
          customClass: 'message-global',
        })
        return
      }

      if (this.codeCorrect != this.codeInput) {
        Message({
          message: '验证码不正确',
          type: 'error',
          customClass: 'message-global',
        })
        return
      }

      if (this.passwordlv == -1) {
        Message({
          message: '请确保密码长度大于8位',
          type: 'error',
          customClass: 'message-global',
        })
        return
      }

      if (this.passwordVerified == 'no') {
        Message({
          message: '两次输入密码不一致',
          type: 'error',
          customClass: 'message-global',
        })
        return
      }

      const registerRequest = async function (data) {
        return await request.post('/user/register', data)
      }

      registerRequest(this.formData)
        .then((res) => {
          if (res.data.code === 200) {
            Message({
              message: '注册成功',
              type: 'success',
              customClass: 'message-global',
            })
            this.$router.push('/login')
          } else {
            Message({
              message: '出错啦',
              type: 'error',
              customClass: 'message-global',
            })
          }
        })
        .catch((err) => {
          Message({
            message: err,
            type: 'error',
            customClass: 'message-global',
          })
        })
    },
  },
}
</script>

<style scoped>
.regMain {
  height: 100%;
  width: 100%;
  user-select: none;
}

.regCard {
  /* vertical-align: middle; */
  /* text-align: center; */
  position: absolute;
  left: 50%;
  top: 50%;
  height: 550px;
  margin-left: -330px;
  margin-top: -275px;
  width: 660px;
  box-shadow: 3px 3px 3px 3px;
  padding-bottom: 1px;
  padding-top: 5px;
  border-radius: 5px;
  background-color: rgba(255, 255, 255, 0.8);
}

.el-form-item {
  margin-left: 50px;
  margin-right: 30px;
  height: 35px;
}

:deep .el-input {
  width: 300px;
  height: 35px;
  margin-left: 10px;
}
</style>